/*
 * DCE400服务系统 -- 后端服务接口 -- 数据访问层 -- 业务员数据访问
 * 包括：业务员数据库增删改查
 *      业务员登录记录插入、查找
 */
package dao

import (
	"errors"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server_attence/app/entity"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server_attence/app/global"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/db"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/util"
	"go.uber.org/zap"
	"strings"
	"time"
)

//********************************************
//Func  ：查询操作员列表，分页查询。
//Method：GET
//Usage ：
//********************************************
func QueryOperatorList(page, pageSize int, mobile string, deptId int64) (int64, []*entity.Operator, error) {
	offset := (page - 1) * pageSize
	session := db.Session().Table("operator")
	defer session.Close()
	var curOperator entity.Operator
	if mobile != "" { //根据mobile查找用户，如果用户是Admin授权，则可以查全部，否则只能输出自己
		has, _ := session.Where("mobile=?", mobile).Get(&curOperator)
		if has {
			if !curOperator.IsAdmin { //非管理员，只能查自己
				session = session.Where("mobile=?", mobile)
			}
		}
	}

	if deptId > 0 {
		session = session.Where("dept_id = ?", deptId)
	}
	if pageSize > 0 {
		session.Limit(pageSize, offset)
	}
	operators := []*entity.Operator{}

	total, err := session.Omit("password").FindAndCount(&operators)
	if err != nil {
		return 0, nil, err
	}
	return total, operators, nil
}

//********************************************
//Func  ：查询指定操作员详情
//Method：GET
//Param：operatorId操作员ID
//Usage ：
//********************************************
func QueryOperatorDetail(mobile string, operatorId int64) (*entity.Operator, error) {
	session := db.Session().Table("operator") //.Where("id=?",operatorId).Get(&operator)
	defer session.Close()

	if operatorId > 0 {
		session = session.Where("id=?", operatorId)
	}
	if mobile != "" {
		session = session.Where("mobile=?", mobile)
	}
	var operator entity.Operator
	has, err := session.Get(&operator)
	if err != nil || has == false {
		return nil, err
	}
	return &operator, nil
}

func InsertOperatorLoginLog(log entity.OperatorLoginLog) error {
	//登陆验证过了，需要搞一个token吗？
	session := db.Session().Table("operator_login_log")
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return err
	}
	_, err = session.Insert(&log) //插入
	if err != nil {
		return err
	}
	err = session.Commit()
	return err
}

//********************************************
//Func  ：添加新操作员（使用手机号作为唯一ID）
//Method：POST
//Usage ：
//********************************************
func InsertOperator(operator entity.Operator) (*entity.Operator, error) {
	var err error
	if len(strings.TrimSpace(operator.Name)) <= 0 { //姓名（必填）/单位名称
		return nil, errors.New("name is none")
	}
	if len(strings.TrimSpace(operator.Mobile)) <= 0 { //手机（必填）
		return nil, errors.New("mobile is none")
	}
	operator.Id = util.GenSnowflakeInt64()
	operator.CreatedAt = time.Now()

	session := db.Session().Table("operator")
	defer session.Close()

	err = session.Begin()
	if err != nil {
		return nil, err
	}

	_, err = session.Insert(&operator) //插入
	if err != nil {
		session.Rollback()
		return nil, err
	}

	err = session.Commit()
	if err != nil {
		global.Log.Error("AddNewOperator commit failed, Error:", zap.Any("error", err))
	}

	var newer entity.Operator
	db.Session().Table("operator").
		Where("mobile =?", operator.Mobile).
		Desc("id").Get(&newer)

	return &newer, nil
}

//********************************************
//Func  ：更新Operator信息
//Method：POST
//Usage ：
//********************************************
func UpdateOperator(operator entity.Operator) error {
	var err error
	if len(strings.TrimSpace(operator.Name)) <= 0 { //姓名（必填）/单位名称
		return errors.New("name is none")
	}
	if len(strings.TrimSpace(operator.Mobile)) <= 0 { //手机（必填）
		return errors.New("mobile is none")
	}

	session := db.Session().Table("operator")
	defer session.Close()
	err = session.Begin()
	if err != nil {
		return err
	}

	_, err = session.Where("mobile=?", operator.Mobile).Cols("name,telephone,email,dept_id,dept_name").Update(operator) //插入
	if err != nil {
		session.Rollback()
		return err
	}
	err = session.Commit()
	return err
}

//********************************************
//Func  ：Operator删除
//Method：DELETE
//Usage ：操作员-账号注销
//********************************************
func DeleteOperator(mobile string, operatorId int64) error {
	if mobile == "" && operatorId <= 0 {
		return errors.New("未指定操作员信息")
	}

	session := db.Session().Table("operator")
	defer session.Close()

	if operatorId > 0 {
		session = session.Where("id=?", operatorId)
	}
	if mobile != "" {
		session = session.Where("mobile=?", mobile)
	}
	var operator entity.Operator
	operator.Id = operatorId
	operator.Mobile = mobile
	session.Begin()
	_, err := session.Delete(&operator)
	if err != nil {
		session.Rollback()
		return err
	}
	err = session.Commit()
	return err
}

//********************************************
//Func  ：更新操作员手机号
//Method：POST
//Usage ：操作员设置-绑定手机
//********************************************
func UpdateOperatorMobile(mobile string, operatorId int64, newMobile string) error {
	var err error
	if len(strings.TrimSpace(mobile)) <= 0 { //手机（必填）
		return errors.New("mobile is none")
	}
	if len(strings.TrimSpace(newMobile)) <= 0 { //新手机（必填）
		return errors.New("new mobile is none")
	}
	if operatorId <= 0 {
		return errors.New("id is error")
	}

	session := db.Session().Table("operator")
	defer session.Close()
	if operatorId > 0 {
		session = session.Where("id=?", operatorId)
	}
	if mobile != "" {
		session = session.Where("mobile=?", mobile)
	}

	var operator entity.Operator
	operator.Mobile = newMobile
	operator.Id = operatorId
	operator.Mobile = mobile

	err = session.Begin()
	if err != nil {
		return err
	}

	_, err = session.Cols("mobile").Update(operator)
	if err != nil {
		session.Rollback()
		return err
	}
	err = session.Commit()
	return err
}

//********************************************
//Func  ：操作员修改密码（验证原密码后，刷新新密码）
//Method：POST
//输入：手机号、旧密码、新密码
//Usage ：
//********************************************
func OperatorChangePassword(mobile string, operatorId int64, pwdSum string) error {
	var err error
	if len(strings.TrimSpace(mobile)) <= 0 && operatorId <= 0 {
		return errors.New("mobile or id is none")
	}
	if len(strings.TrimSpace(pwdSum)) <= 0 { //PASSWORD
		return errors.New("new mobile is none")
	}
	if operatorId <= 0 {
		return errors.New("custom id is none")
	}

	session := db.Session().Table("operator")
	defer session.Close()
	if operatorId > 0 {
		session = session.Where("id=?", operatorId)
	}
	if mobile != "" {
		session = session.Where("mobile=?", mobile)
	}

	var operator entity.Operator
	operator.Password = pwdSum

	err = session.Begin()
	if err != nil {
		return err
	}

	_, err = session.Cols("password").Update(operator)
	if err != nil {
		session.Rollback()
		return err
	}
	err = session.Commit()
	return err
}
